package service.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import kafka.javaapi.consumer.ConsumerConnector;
import play.Play;
import service.MessagesQueue;
import utils.LogUtil;
import bp.DataSynBP;

public class PayRecordsMessageQueue implements MessagesQueue {

	private static Queue<String> queue = new LinkedList<String>();
	private int consumethreshold=Integer.parseInt(Play.configuration.getProperty("SYNC_CONSUMER_BATCH_SIZE", "1000"));
	private static ConsumerConnector consumer;
	public static void setConsumer(ConsumerConnector consumer) {
		PayRecordsMessageQueue.consumer = consumer;
	}

	private static PayRecordsMessageQueue ticketmessagequeue;
	
	public static PayRecordsMessageQueue getInstance(){
		synchronized(PayRecordsMessageQueue.class){
			if(ticketmessagequeue==null){
				ticketmessagequeue = new PayRecordsMessageQueue();
//				ticketmessagequeue.consumethreshold = SystemParam.SYNC_CONSUMER_BATCH_SIZE;
			}
		}
		return ticketmessagequeue;
	}

	@Override
	public void addMessage(String message) throws Exception {
		synchronized(queue){
			queue.offer(message);
		}
		checkqueuesize();
	}
	
	private int checkqueuesize() throws Exception{
		try {
			if(queue.size()>0 && (queue.size()%consumethreshold==0)){
				consumeMessages(1);
			}
		} catch (Exception e) {
			LogUtil.logerror("consumeMessages（）消费批量消息失败", e);
		}
		return 0;
	}

	@Override
	public List<String> getMessages(int size) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
		
	private PayRecordsMessageQueue(int consumethreshold) {
		super();
		this.consumethreshold = consumethreshold;
	}
	
	private PayRecordsMessageQueue(){
		super();
	}

	public synchronized int consumeMessages(int type) throws Exception{
		synchronized(queue){
			try {
				String message;
				List<String> messages = new ArrayList<String>();
				while((message=queue.poll())!=null){
					messages.add(message);
				}
				if(messages.size()>0){
					DataSynBP datasynbp = new DataSynBP();
					datasynbp.payrecordsync(messages);
					consumer.commitOffsets();
				}
			} catch (Exception e) {
				LogUtil.logerror("consumeMessages（）消费批量自助机支付信息消息失败", e);
			}
		}
		return 0;
	}


}
